#include "uart.h"
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#include "gps.h"

unsigned char xdata uartBuffer[UART_BUFFER_SIZE];
unsigned char xdata uartBufferIndex;
unsigned char xdata xmitFlag;
unsigned char xdata pos_line[30];
unsigned char xdata temp_pos_str[11];
unsigned int xdata temp_int;
unsigned int xdata curr_alt = 0;
float xdata curr_speed = 0, prev_speed = 0, trip = 0;
float xdata odometer = 0;
unsigned char xdata sentence_ready = 0;
int xdata temp;
float temp_pos;

void get_field(unsigned char* buf, unsigned char* target, unsigned char max_len, unsigned char field_no){

	unsigned char xdata i, j;

	memset(target, 0, max_len);
	j = 0;
	i = 0;
	while(j < field_no){
		if(buf[i] == ',')
			j++;
		i++;
	}
	j = 0;
	
	while(buf[i] != ',')
		target[j++] = buf[i++];	
}

void ISR_UART() interrupt 4{

	xdata unsigned char ch;

	if (TI0)
	{
		// Transmitting a byte
		xmitFlag = 1;
		TI0 = 0;
	}
	else
	{
		// Receiving a byte
		ch = SBUF0;
		if(sentence_ready){
			RI0 = 0;
			return;
		}
		
		// Watch for buffer size. This shouldn't happen, but discard if needed.
		if (uartBufferIndex >= UART_BUFFER_SIZE || ch == '$')
		{
			uartBufferIndex = 0;
			//memset(uartBuffer, 0, sizeof uartBuffer);
		}

		uartBuffer[uartBufferIndex] = ch;

		if (ch == '\n' && uartBuffer[0] == '$')
		{
			uartBuffer[uartBufferIndex] = '\0';
			uartBufferIndex = 0;

			//          1         2         3         4         5         6     	7
			//01234567890123456789012345678901234567890123456789012345678901234567890123
			//$GPRMC,225446.000,A,4916.4500,N,12311.1200,W,000.5,054.7,191194,020.3,E*68
			//    0    1        2     3     4     5   6    7      8      9	   10
			//-12.45675, -012.12341
			if (uartBuffer[3] == 'R' && uartBuffer[4] == 'M' && uartBuffer[5] == 'C')
			{
				if(uartBuffer[18] == 'A'){
					sentence_ready = GPRMC_READY;
					have_fix = 1;				
				}
		
				
				
			}
			else if (uartBuffer[2] == 'P' && uartBuffer[3] == 'G' && uartBuffer[4] == 'G'){
				
				sentence_ready = GPGGA_READY;
			}
			//$DUMP
			else if (uartBuffer[1] == 'D' && uartBuffer[2] == 'U')
				sentence_ready = GPS_DUMP;
				
		}
		else
		{
			uartBufferIndex++;
		}
		
		// Clear the receive interrupt flag
		RI0 = 0;
	}

}

/*
void UartWrite(unsigned char ch)
{
	// Clear TI0
	xmitFlag = 0;
	//SCON0 = SCON0 & 0xFD;
	SBUF0 = ch;
	// Wait for TI0 to be set
	while (!xmitFlag);

	
}
*/
/*
void UartArrayWrite(unsigned char* buf, short len){
	unsigned short i;
	for(i = 0; i < len; i++){
		xmitFlag = 0;
		SBUF0 = buf[i];
		// Wait for TI0 to be set
		while (xmitFlag == 0) ;
	}
}
*/
/*

void UartWriteText(unsigned char* str)
{
	while (*str != '\0')
	{
		UartWrite(*str);
		str++;
	}
}
*/